import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class Webview extends StatefulWidget {
  final String url;
  final String statusBarColor;
  final String title;
  final bool hideAppbar;
  final bool backForbid;

  Webview({Key key, this.url,this.statusBarColor, this.title, this.hideAppbar, this.backForbid = false}) : super(key : key);

  @override
  _WebviewState createState() => _WebviewState();
}

class _WebviewState extends State<Webview> {

  final webviewReference = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription<WebViewStateChanged> _onUrlStatusChanged;
  StreamSubscription<WebViewHttpError> _onUrlErrorChanged;
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _onUrlChanged.cancel(); // 取消监听
    _onUrlStatusChanged.cancel();
    _onUrlErrorChanged.cancel();
    webviewReference.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   _onUrlChanged = webviewReference.onUrlChanged.listen((String url){

    });
    _onUrlStatusChanged = webviewReference.onStateChanged.listen((WebViewStateChanged state){
      if(state.type == WebViewState.startLoad){
        
      }
    });

    _onUrlErrorChanged = webviewReference.onHttpError.listen((WebViewHttpError err){

    });
  }

  _appbar(Color backgroundColor, Color backButtonColor){
    if (widget.hideAppbar ?? false) {
      Container(
        height: 40,
        color: backgroundColor,
      );
    } else {
      return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            InkWell(
              onTap: (){
                Navigator.of(context).pop();
              },
              child: Container(
                padding: const EdgeInsets.only(left: 10,top: 30),
                width: 40,
                child: Icon(Icons.close, color: backButtonColor,),
              ),
            ),
            FractionallySizedBox(
              child: Container(
                color: Colors.black,
                child: Text("Webview", style: TextStyle(color: Colors.black),textAlign: TextAlign.end,),
              ),
            ),
            Container(
              width: 40,
            )
          ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          _appbar(null, null),
          Expanded(
            child: WebviewScaffold(
              url: widget.url,
              withZoom: true,
              withLocalStorage: true,
              hidden: true,
              initialChild: Container(
                color: Colors.white,
                child: Center(
                  child: Text("Loading..."),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}